package org.example.adb;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

//1.检查已连接的设备
public class AdbExample {
    public static void main(String[] args) {
        List<String> devices = getConnectedDevices();
        if (devices.isEmpty()) {
            System.out.println("No devices connected.");
        } else {
            System.out.println("Connected devices:");
            for (String device : devices) {
                System.out.println(device);
            }
        }
    }

    public static List<String> getConnectedDevices() {
        List<String> devices = new ArrayList<>();
        try {
            ProcessBuilder builder = new ProcessBuilder("adb", "devices");
            Process process = builder.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            boolean listStart = false;
            while ((line = reader.readLine()) != null) {
                if (line.trim().equals("")) continue;
                if (line.startsWith("List of devices")) {
                    listStart = true;
                    continue;
                }
                if (listStart) {
                    String[] parts = line.split("\\s+");
                    if (parts.length >= 2 && parts[1].equals("device")) {
                        devices.add(parts[0]);
                    }
                }
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return devices;
    }
}
